# 编写自动化脚本完成商城项目登录->浏览商品->下单功能（使用显式等待）

from selenium import  webdriver
from selenium.webdriver.common.by import By
from time import sleep
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

# 封装的意思：把相同类似的代码放到一个函数里面,重复使用
def wait_element_clickable(locator):
    web_element = WebDriverWait(driver,8,0.5).until(EC.element_to_be_clickable(locator))
    return web_element

def wait_element_visible(locator):
    #web_element代表通过显示等待找到的元素
    web_element =  WebDriverWait(driver, 8, 0.5).until(EC.visibility_of_element_located(locator))
    return web_element

driver = webdriver.Chrome()
driver.get('http://mall.lemonban.com:3344/')
driver.maximize_window()
# 登录
loc_login = (By.XPATH,'//a[text()="登录"]')
# 用户名输入框
loc_username = (By.XPATH,'//input[@placeholder="请输入手机号/用户名"]')
# 密码输入框
loc_password = (By.XPATH,'//input[@placeholder="请输入密码"]')
# 登录按钮
loc_login_but = (By.CLASS_NAME,'login-button')

wait_element_clickable(loc_login).click()
wait_element_visible(loc_username).send_keys('lemon_py')
wait_element_visible(loc_password).send_keys('12345678')
wait_element_clickable(loc_login_but).click()
# 强制等待
sleep(2)
loc_pro_list = (By.LINK_TEXT,'商品列表')
loc_pro_name = (By.XPATH,'//div[contains(text(),"lucky跑鞋04")]')
loc_buy = (By.CLASS_NAME,'buy-now')
loc_submit_order = (By.LINK_TEXT,'提交订单')
# 点击商品列表
wait_element_clickable(loc_pro_list).click()
# 点击商品名字
wait_element_clickable(loc_pro_name).click()
# 点击立即购买
wait_element_clickable(loc_buy).click()
# 点击提交订单
wait_element_clickable(loc_submit_order).click()

sleep(3)
driver.quit()